'use strict';
const unipay = require('uni-pay');
const configCenter = require("uni-config-center");
// 读取配置中心配置
var unipayConfig = configCenter({
	pluginId: 'uni-pay'
}).requireFile('config.js');
// 读取配置中心配置
var wxConfig = configCenter({
	pluginId: 'wx-login'
}).requireFile('config.js');

exports.main = async (event, context) => {
	console.log('event : ', event);
	const unipayIns = unipay.initWeixin({
		appId: wxConfig.appId,
		mchId: unipayConfig.wxpay.mp.mchId,
		key: unipayConfig.wxpay.mp.key,
	});
	let res = await unipayIns.checkNotifyType(event);
	console.log('checkNotifyType res : ', res);
	if (res === 'refund') {
		// 退款通知
	} else if (res === 'payment') {
		// 支付结果通知
		let result = await unipayIns.verifyPaymentNotify(event);
		console.log('verifyPaymentNotify result : ', result);
		// verifyPaymentNotify result :  {
		//   openid: 'o7jaQ7btR2zoprdAs7StfSkK9JWc',
		//   sign: 'B7980A69F23E53D099B5BBF2E9222A42',
		//   bankType: 'OTHERS',
		//   cashFee: 8,
		//   feeType: 'CNY',
		//   isSubscribe: 'N',
		//   mchId: '1685118048',
		//   nonceStr: 'eikvmm11b80u95qi',
		//   outTradeNo: '6758f114c8838be8d8afb37f',
		//   resultCode: 'SUCCESS',
		//   returnCode: 'SUCCESS',
		//   timeEnd: '20241211095545',
		//   totalFee: 8,
		//   tradeType: 'JSAPI',
		//   transactionId: '4200002446202412114014582921',
		//   appId: 'wx3f4d29ad53d2bfa9',
		//   couponList: []
		// }
		const updateRes = await uniCloud.callFunction({
			name: 'xxf-order',
			data: {
				action: "updateOrderStatus",
				orderId: result.outTradeNo,
				status: '2',
				notifyInfo: result,
				pay_time: Date.now(),
				pay_money: result.totalFee
			}
		});
		console.log("updateRes: ", updateRes);
	}
	// 微信支付V2处理成功之后
	return {
		mpserverlessComposedResponse: true,
		statusCode: 200,
		headers: {
			'content-type': 'text/xml;charset=utf-8'
		},
		body: `<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`
	}
};